<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    :modal="model"
    top="5vh"
    :title="state.dialogTitle"
    :width="width"
    draggable
  >
    <el-form
      ref="dataFormRef"
      v-loading="state.loading"
      :model="form"
      :rules="dataRules"
      label-width="100px"
      :disabled="state.operType === 'view'"
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item :label="translate('flow.def.flowName')" prop="flowName">
            <el-input
              v-model="form.flowName"
              :placeholder="translate('flow.def.flowName')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="translate('flow.def.flowKey')" prop="flowKey">
            <el-input
              v-model="form.flowKey"
              type="text"
              :disabled="disabledFlowKey"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="icon" label="设置图标">
            <IconEdit v-model="form.icon" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="translate('flow.def.groupId')" prop="groupId">
            <DictSelect
              v-model:defaultValue="form.groupId"
              dict-code="flow-group"
              :width="300"
              placeholder="请选择流程分组"
              show-all="N"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="formId" label="流程表单">
            <el-input v-model="form.formName" placeholder="请设置流程表单">
              <template #append>
                <el-button icon="Search" @click="handleOpenFormPicker" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="translate('flow.def.status')" prop="status">
            <DictSelect
              v-model:default-value="form.status"
              dict-code="order_status"
              expanding
              show-all="N"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="translate('flow.def.sort')" prop="sort">
            <el-input-number
              v-model="form.sort"
              :min="1"
              :max="1000"
              :placeholder="translate('flow.def.sort')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="translate('flow.def.remark')" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :placeholder="translate('flow.def.remark')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-if="state.operType !== 'view'" #footer>
      <span class="dialog-footer">
        <el-button type="warning" @click="close">{{
          translate("buttons.cancel")
        }}</el-button>
        <el-button type="primary" :disabled="state.loading" @click="onSubmit">
          {{ translate("buttons.confirm") }}</el-button
        >
      </span>
    </template>
    <FormPicker ref="formPickerRef" @change="handleFormChange" />
  </el-dialog>
</template>

<script setup name="DefFlowDialog">
import { useMessage } from "@/hooks/message";
import { getObj, addObj, validFlowKey, updateObj } from "@/api/flow/def";
import { ref } from "vue";
import { validNumber } from "@/utils/rules";
import { translate } from "@/plugins/i18n";
import DictSelect from "@/components/dictSelect.vue";
import FormPicker from "@/components/formPicker.vue";

const props = defineProps({
  title: {
    type: String,
    default: "流程定义"
  },
  width: {
    type: String,
    default: "60%"
  },
  model: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(["refresh"]);

// 定义变量内容
const dataFormRef = ref();
const formPickerRef = ref(null);
const disabledFlowKey = ref(false);

onMounted(() => {});

const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  loading: false,
  operType: false
});

// 提交表单数据
const form = reactive({
  id: "",
  flowName: "",
  flowKey: "",
  icon: {
    name: "file-icons:omnigraffle",
    bgc: "#4C87F3",
    color: "#FFFFFF"
  },
  formId: "",
  formName: "",
  status: "-1",
  groupId: "",
  version: null,
  remark: "",
  sort: 1
});

// 校验是否已存在
const validateFlowKey = (rule, value, callback) => {
  // 修改判断相同id
  validFlowKey({
    searchKey: value,
    id: form.id,
    status: form.status,
    version: form.version
  }).then(response => {
    const result = response.code;
    if (result !== 200) {
      callback(new Error("流程key已经存在"));
    } else {
      callback();
    }
  });
};

// 定义校验规则
const dataRules = ref({
  flowName: [
    {
      required: true,
      message: "流程名称不能为空",
      trigger: "blur"
    },
    { min: 2, max: 20, message: "流程名称长度在2~20", trigger: "blur" }
  ],
  flowKey: [
    { required: true, message: "流程KEY不能为空", trigger: "blur" },
    { validator: validateFlowKey, trigger: "blur" }
  ],
  groupId: [{ required: true, message: "分组名称不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  sort: [
    { required: true, message: "排序值不能为空", trigger: "blur" },
    { validator: validNumber, message: "排序值只能是数字", trigger: "blur" }
  ]
});

const handleOpenFormPicker = () => {
  formPickerRef.value.show();
};

const handleFormChange = rows => {
  form.formId = rows[0].id;
  form.formName = rows[0].formName;
};

// 打开弹窗
const show = (type, id) => {
  state.dialogVisible = true;
  state.operType = type;
  form.id = "";
  if (type === "add") {
    state.dialogTitle = "新增";
  } else if (type === "edit") {
    state.dialogTitle = "修改";
  } else if (type === "view") {
    state.dialogTitle = "查看";
  }
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
  // 获取DefFlow信息
  if (id) {
    form.id = id;
    disabledFlowKey.value = true;
    getDefFlowData(id);
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;
  try {
    state.loading = true;
    form.flowIcon = JSON.stringify(form.icon);
    if (form.id) {
      await updateObj(form);
    } else {
      await addObj(form);
    }
    useMessage().success("保存成功");
    close();
    emit("refresh");
  } catch (err) {
    useMessage().warning(err.msg);
  } finally {
    state.loading = false;
  }
};

const close = () => {
  state.dialogTitle = props.title;
  dataFormRef.value?.resetFields();
  state.dialogVisible = false;
};

// 初始化表单数据
const getDefFlowData = id => {
  // 获取数据
  state.loading = true;
  getObj(id)
    .then(res => {
      Object.assign(form, res.data);
    })
    .finally(() => {
      state.loading = false;
    });
};

// 暴露变量
defineExpose({
  show,
  close
});
</script>
